/*
 * main.cpp
 * asd
 *  Created on: Feb 11, 2011
 *      Author: alki
 */
#define _USE_MATH_DEFINES

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

#include "SDL.h"
#include "objekte/Objekt.h"
#include "math/Vektor.h"
#include "math/Gerade.h"
#include "math/Ebene.h"
#include "math/Matrix.h"
#include "Ctimer.h"
#include "Szene.h"
#include "Thread.h"

using namespace std;

#include "programmierung/variablen.def"

long treetimer=0;

#include <list>

int main( int argc, char **argv )
{
	try {
		SDL *sdl = new SDL(screen_width,screen_height,32,false);
		Szene *szene = new Szene(screen_width,screen_height,jitter_filter,diffus_filter,maximale_tiefe);
		szene->setPosition(Vektor(0,0,1.2));
		szene->setDirection(Vektor(0,0,-1));
		szene->LoadFile(filename);
		FARBE color[screen_width*screen_height];

		Thread *threads = new Thread[maximal_threads];
		for(unsigned int i=0;i<maximal_threads;i++) {
			threads[i].SetSzene(szene);
			threads[i].SetFarbe(color);
		}


		bool berechnet=false;

		while ( !sdl->done() )
		{
			sdl->PollEvent();
			if (!berechnet) {
				berechnet=true;

				Ctimer *timer = new Ctimer();
				timer->start();

				for(unsigned int y=0,x=0;y<screen_height;x++) {
					bool inserted=false;
					if(x>=screen_width) {
						x%=screen_width;
						y++;
						if((y%10)==0) cout << y << endl;
					}
					while(!inserted) {
						for(unsigned int i=0;i<maximal_threads;i++) {
							if(threads[i].GetSize()<maximal_ppt) {
								threads[i].Add(x,y);
								inserted=true;
								break;
							}
						}
						if(inserted) break;
						else usleep(1);
					}
				}

				bool threads_finished=false;
				while(!threads_finished) {
					threads_finished=true;
					for(unsigned int t=0;t<maximal_threads;t++) {
						if(!threads[t].finished()) {
							threads_finished=false;
						}
						else {
							threads[t].End();
						}
					}
					usleep(1);
				}
				sdl->GetGL()->BeginDraw();
				sdl->GetGL()->BeginPoints();
				for(unsigned int x=0;x<screen_width;x++) {
					for(unsigned int y=0;y<screen_height;y++) {
						sdl->GetGL()->DrawPoint(x,y,color[x+y*screen_width].r,color[x+y*screen_width].g,color[x+y*screen_width].b);
					}
				}
				sdl->GetGL()->EndPoints();
				sdl->GetGL()->EndDraw();

				cout << "Time: " << timer->stop() << endl;
				delete timer;
				cout << "Tree: " << treetimer << endl;
			}

			sdl->PollEvent();
		}

		delete [] threads;
		delete szene;
		delete sdl;
	}
	catch(Exception *e) {
		e->out();
	}
	catch(...) {
		cout << "seltsamer Fehler!" << endl;
	}

    return( 0 );
}
